import React from 'react';
import { Form, Input, Upload, Button, notification, Switch, InputNumber } from 'antd';
import { connect } from 'umi';
import UploadUtil from '@/components/UploadUtil';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';

class AddForm extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      data: {},
      imageUrl: '',
      imgList: [],
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    console.log(this.props);
    this.fetchData();
  }
  fetchData = () => {
    if (this.props.cateid > 0) {
      this.setState({ loading: true });
      this.props
        .dispatch({
          type: 'Abp/get',
          payload: { Id: this.props.cateid },
          control: 'Category',
        })
        .then(() => {
          var result = this.props.response.result;
          if (result.icons) {
            this.setState({ imageUrl: UploadUtil.imgServ + result.icons });
          }
          this.formRef.current.setFieldsValue({ category: result });
          this.setState({ loading: false });
        });
    }
    if (this.props.parentCate.id > 0 && this.props.cateid == 0) {
      let cateobj = {
        id: this.props.cateid,
        parentId: this.props.parentCate.id,
        level: this.props.parentCate.level + 1,
        layout: this.props.layout,
      };
      this.formRef.current.setFieldsValue({ category: cateobj });
    } else {
      let cateobj = {
        id: 0,
        parentId: 0,
        level: 1,
        layout: this.props.layout,
      };
      this.formRef.current.setFieldsValue({ category: cateobj });
    }
  };
  onFinish = async (values: any) => {
    this.setState({ loading: true });
    let _action = 'Abp/create';
    if (values.category.id > 0) _action = 'Abp/update';

    if (this.state.imgList && this.state.imgList.length > 0) {
      var pic = await UploadUtil.uploadPic(
        this.state.imgList,
        values.category.id,
        'Category',
        'icons',
      );
      values.category.icons = pic;
    }
    this.props
      .dispatch({
        type: _action,
        payload: values.category,
        control: 'Category',
      })
      .then(() => {
        this.setState({ loading: false });
        if (this.props.response.success) {
          notification['success']({
            message: 'Notice',
            description: '恭喜，更新成功！',
          });
          this.props.RefreshData();
        } else {
          console.log(this.props.response);
          notification['error']({
            message: 'Error',
            description: '操作失败，请联系系统管理员。',
          });
        }
      });
  };
  handleUpload = (info: any) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      UploadUtil.getBase64(info.file.originFileObj, (imageUrl: any) =>
        this.setState({
          imageUrl,
          imgList: info.fileList,
          loading: false,
        }),
      );
    }
  };
  render() {
    const { imageUrl, loading } = this.state;
    const layout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    };
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    return (
      <Form {...layout} ref={this.formRef} name="nest-messages" onFinish={this.onFinish}>
        <Form.Item
          name={['category', 'categoryName']}
          label="分类名"
          rules={[{ required: true, message: '分类名必填' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name={['category', 'categoryIndex']}
          label="分类索引"
          rules={[{ required: true, message: '分类索引必填' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name={['category', 'layout']}
          label="所属模块"
          rules={[{ required: true, message: '模块必填' }]}
        >
          <Input disabled={true} />
        </Form.Item>
        <Form.Item name={['category', 'isHide']} label="是否隐藏" valuePropName="checked">
          <Switch />
        </Form.Item>
        <Form.Item name={['category', 'no']} label="序号">
          <InputNumber />
        </Form.Item>
        <Form.Item name={['category', 'parentId']} label="上级分类">
          <Input />
        </Form.Item>
        <Form.Item label="分类图标">
          <Upload
            action={UploadUtil.mockURL}
            name="files"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            beforeUpload={UploadUtil.beforeUpload}
            onChange={this.handleUpload}
          >
            {imageUrl ? <img src={imageUrl} style={{ width: '100%' }} /> : uploadButton}
          </Upload>
        </Form.Item>
        <div hidden={true}>
          <Form.Item name={['category', 'id']}>
            <Input />
          </Form.Item>
          <Form.Item name={['category', 'level']}>
            <Input />
          </Form.Item>
          <Form.Item name={['category', 'icons']}>
            <Input />
          </Form.Item>
        </div>
        <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 6 }}>
          <Button type="primary" htmlType="submit" loading={this.state.loading}>
            确定
          </Button>
        </Form.Item>
      </Form>
    );
  }
}

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(AddForm);
